package edu.suda.xsap.controller;

import edu.suda.xsap.common.Result;
import edu.suda.xsap.dto.EmployeeDto;
import edu.suda.xsap.entity.Employee;
import edu.suda.xsap.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/teacher")
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @GetMapping("/list")
    public Result list() {
        //1. 参数处理
        //2. 调用业务层方法，并做异常处理
        try {
           List<EmployeeDto> lst = employeeService.findAll();
            //
            return Result.success(lst);
        } catch (Exception e) {
            log.error("查询失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }

    @PostMapping("/add")
    //从前端接受json
    public Result add(@RequestBody Employee employee) {
        try {

            employee.setLastModifyTime(LocalDateTime.now());
            System.out.println("前端数据：" + employee);
            employeeService.save(employee);
            return Result.success();
        } catch (Exception e) {
            log.error("添加失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }

    @PutMapping("/update")
    public Result update(@RequestBody Employee employee) {
        try {
            employee.setLastModifyTime(LocalDateTime.now());
            employeeService.update(employee);
            return Result.success();
        } catch (Exception e) {
            log.error("修改失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        try {
            employeeService.delete(id);
            return Result.success();
        } catch (Exception e) {
            log.error("删除失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }
    @GetMapping("/find/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        try {
            EmployeeDto employeeDto = employeeService.findById(id);
            return Result.success(employeeDto);
        } catch (Exception e) {
            log.error("查询失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }

}
